//
//  EnemyCharacterNode.m
//  iFly
//
//  Created by User-23 on 12/13/14.
//  Copyright (c) 2014 TeamDifferent. All rights reserved.
//

#import "EnemyCharacterNode.h"
#import "Constants.h"
#import "FireBallEnemy.h"
#import "CharacterNode.h"
#import "GameOverScene.h"
#import "SoundHandler.h"

@implementation EnemyCharacterNode

+(instancetype)enemyCharacterWithPosition:(CGPoint)position inScene:(SKScene *)scene {
    
    EnemyCharacterNode* enemyCharacter = [self spriteNodeWithImageNamed:@"lokiEnemy.png"];
    
    //setting physical logic for the enemy character
    //enemyCharacter.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:enemyCharacter.size];
    enemyCharacter.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:enemyCharacter.size.width/2 center:enemyCharacter.anchorPoint];
    enemyCharacter.physicsBody.affectedByGravity = NO;
    enemyCharacter.physicsBody.categoryBitMask = obstacleCategory;
    enemyCharacter.physicsBody.dynamic = YES;
    enemyCharacter.physicsBody.contactTestBitMask = weaponsCategory;
    enemyCharacter.physicsBody.collisionBitMask = 0;
    enemyCharacter.name = @"enemyCharacter";
    enemyCharacter.position = position;
    
    //setting properties of the enemy character
    enemyCharacter.health = enemyCharacterHealth;
    enemyCharacter.isDead = NO;
    
    
    return enemyCharacter;
}

-(void) flyIn {
    SKAction* move = [SKAction moveByX:-(flyingInOffset+self.size.width) y:0 duration:2];
    [self runAction:move completion:^{
        [self shoot];
    }];
}

-(void)move {
    static BOOL movingUp = YES;
    NSInteger distance = arc4random()%200;
    CGPoint target;
    
    if(movingUp){
        if ((self.position.y + distance) < self.parent.scene.size.height-minY-self.size.height/2) {
            target = CGPointMake(self.position.x, self.position.y+distance);
        }
        else{
            target = CGPointMake(self.position.x, self.parent.scene.size.height-minY-self.size.height/2);
        }
    }
    else {
        if((self.position.y - distance) > minY + self.size.height/2) {
            target = CGPointMake(self.position.x, self.position.y-distance);
        }
        else {
            target = CGPointMake(self.position.x, minY + self.size.height/2);
        }
    }
    
    movingUp = !movingUp;
    SKAction* move = [SKAction moveTo:target duration:1.0];
    [self runAction:move];
}

-(void)shoot {
    SKAction* prepareShoot = [SKAction runBlock:^{
        
        //checking if loki is dead to stop the endless loop of actions
        if (self.isDead) {
            return;
        }
        
        NSMutableArray* textures = [[NSMutableArray alloc] init];
        
        SKAction* shuffle;
        SKAction* rest;
        
        //random chance for energy ball
        NSInteger random = arc4random_uniform(100);
        BOOL isCharged = NO;
        NSString* textureName = @"lokiS";
        NSInteger health = 2;
        
        if (random < chanceForEnergyBall) {
            textureName = @"lokiWeaponShoot";
            //shoot charged energy ball
            isCharged = YES;
            health = 5;
        }
        
        FireBallEnemy* fireball = [FireBallEnemy fireBallWithPosition:self.position andHealth:health andIsCharged:isCharged];
        [fireball setScale:self.parent.scene.size.height/sceneScaling];
        [self.parent addChild:fireball];
        
        CharacterNode* character = (CharacterNode*)[self.parent childNodeWithName:@"character"];
        [fireball moveToPosition:character.position];
        
        for (int idx = 0; idx < 1; idx++) {
            NSString* currentTextureName = [NSString stringWithFormat:@"%@0%d",textureName,idx];
            SKTexture* texture = [SKTexture textureWithImageNamed:currentTextureName];
            [textures addObject:texture];
        }
        shuffle = [SKAction animateWithTextures:textures timePerFrame:0.5];
        rest = [SKAction setTexture:[textures objectAtIndex:[textures count]-1]];
        SKAction* animateLoki = [SKAction sequence:@[shuffle,rest]];
        [self runAction:animateLoki completion:^{
            [self setTexture:[SKTexture textureWithImageNamed:@"lokiEnemy" ]];
        }];
    }];
    
    SKAction* move = [SKAction runBlock:^{
        //double checking if he's dead..
        if (self.isDead) {
            return;
        }
        else {
            [self move];
        }
    }];
    SKAction* wait = [SKAction waitForDuration:2.0];
    
    SKAction* sequence = [SKAction repeatActionForever:[SKAction sequence:@[prepareShoot,move,wait]]];
    [self runAction:sequence];
}

-(void)wasHit {
    self.health--;
    if (self.health % enemyCharacterHealthTreshold == 0) {
        [[SoundHandler sharedSoundPlayer] playSoundWithName:@"lokiHit" andType:@"wav"];
        SKEmitterNode* lokiSpark = [NSKeyedUnarchiver unarchiveObjectWithFile:[[NSBundle mainBundle] pathForResource:@"LokiSpark" ofType:@"sks"]];
        lokiSpark.position = self.position;
        lokiSpark.name = @"LokiSpark";
        [self.parent.scene addChild:lokiSpark];
        
        SKAction* fadeEmitter = [SKAction fadeAlphaTo:0.0 duration:1.5];
        SKAction* remove = [SKAction removeFromParent];
        SKAction* sequence = [SKAction sequence:@[fadeEmitter, remove]];
        [lokiSpark runAction:sequence];
    }
    
    //checking if enemy character is dead
    if(self.health == 0){
        [[SoundHandler sharedSoundPlayer] playSoundWithName:@"LokkiDyingPain" andType:@"mp3"];
        self.isDead = YES;
        self.physicsBody.categoryBitMask = deadCategory;
        
        
        SKAction* waitBeforeFade = [SKAction waitForDuration:1];
        SKAction* changeTexture = [SKAction runBlock:^{
            [self setTexture:[SKTexture textureWithImageNamed:@"LokiFall.png"]];
        }];
        CGPoint position=CGPointMake(self.position.x+flyingInOffset, self.position.y);
        SKAction* move =[SKAction moveTo:position duration:3.0];

        SKAction* fadeLoki = [SKAction fadeAlphaTo:0.0 duration:2];
        SKAction* waitAfterFade=[SKAction waitForDuration:1];
        SKAction* removeCharacter = [SKAction removeFromParent];
        
        SKAction* presentGameOverScene = [SKAction runBlock:^{
            
            //removing notifications for background
            [[NSNotificationCenter defaultCenter] removeObserver:[self.parent childNodeWithName:@"pause"]];
            
            CharacterNode* character = (CharacterNode*)[self.parent childNodeWithName:@"character"];
            [character addScore:lokiPointsForKill];
            
            SKTransition* reveal = [SKTransition fadeWithDuration:1.0];
            SKScene* gameOverScene=[[GameOverScene alloc] initWithSize:self.parent.scene.size score:character.characterScore gameIsWon:YES];
            [self.parent.scene.view presentScene:gameOverScene transition:reveal];
        }];
        SKAction* sequence = [SKAction sequence:@[waitBeforeFade,changeTexture,fadeLoki,waitAfterFade,presentGameOverScene,removeCharacter]];
        [self runAction:move];
        [self runAction:sequence];  
    }
}



@end
